/**
 * 入住信息管理模块配置文件
 * 该文件定义了入住信息管理模块的相关配置，包括模块名称、接口定义、表格列配置、搜索配置和表单配置。
 * @module stayInfoConfig
 */
import dayjs from 'dayjs'
import { ref } from 'vue'
import type { ApiResponse, ListResponse } from '/@/types/api'
import request from '/@/utils/request'

export const moduleName = '入住信息'
export const moduleApi = '/api/hotelCheckin'

// 导出房屋状态枚举
export type HouseTypeKey = 'STANDARD' | 'LARGE' | 'SUITE'
export type HouseTypeValue = '标准间' | '大床房' | '套房'
export const HOUSE_TYPES: Record<string, string> = {
  STANDARD: '标准间',
  LARGE: '大床房',
  SUITE: '套房',
} as const

// 选项数据类型
interface SelectOption {
  value: string | number
  label: string
  disabled?: boolean
}

/**
 * 酒店选项数据（从API获取）
 */
export const hotelOptions = ref<SelectOption[]>([])

/**
 * 用户选项数据（从API获取）
 */
export const userOptions = ref<SelectOption[]>([])

/**
 * 获取酒店列表
 * @param query 搜索关键词
 */
export const getHotelList = async (query?: string) => {
  try {
    console.log('开始获取酒店列表数据, 搜索关键词:', query)
    const params: Record<string, any> = {
      limit: 10,
      page: 1,
    }

    // 如果有搜索关键词，添加到查询参数
    if (query) {
      params.name = query // 假设后端API支持通过name字段进行模糊搜索
    }

    const res = await request.get<any, ApiResponse<ListResponse<any>>>('/api/hotelManagement', {
      params,
    })

    console.log('酒店API返回数据:', res?.result?.rows)

    if (res?.result?.rows) {
      hotelOptions.value = res.result.rows.map((item: any) => ({
        value: String(item.id),
        label: item.name || `酒店${item.id}`,
      }))
      console.log('处理后的酒店选项:', hotelOptions.value)
    }
  } catch (error) {
    console.error('获取酒店列表失败:', error)
  }
}

/**
 * 获取用户列表
 * @param query 搜索关键词
 */
export const getPlayerList = async (query?: string) => {
  try {
    console.log('开始获取用户列表数据, 搜索关键词:', query)
    const params: Record<string, any> = {
      activityId: localStorage.getItem('hongyouActId') || '',
    }

    // 如果有搜索关键词，添加到查询参数
    if (query) {
      params.name = query // 使用name参数进行搜索
    }

    const res = await request.get<any, ApiResponse<ListResponse<any>>>('/api/player/all', {
      params,
    })

    console.log('用户API返回数据:', res?.result)

    if (res?.result) {
      userOptions.value = res.result.map((item: any) => ({
        value: String(item.userId), // 确保value是用户ID
        label: item.name || item.username || `用户ID:${item.id}`,
      }))
      console.log('处理后的用户选项:', userOptions.value)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

/**
 * 房屋类型选项
 */
export const houseTypeOptions = ref<SelectOption[]>(
  Object.entries(HOUSE_TYPES).map(([value, label]) => ({
    value,
    label,
  }))
)

/**
 * 搜索字段配置
 */
export const searchFields = ref([
  {
    prop: 'userId',
    label: '用户',
    component: 'select',
    placeholder: '请选择用户',
    componentProps: {
      filterable: true,
      remote: true,
      reserveKeyword: true,
      remoteMethod: (query: string) => {
        if (query) {
          console.log('远程搜索用户:', query)
          getPlayerList(query)
        }
      },
      options: userOptions,
      onFocus: () => {
        // 预加载用户列表
        getPlayerList()
      },
    },
  },
  {
    prop: 'phone',
    label: '手机号',
    component: 'input',
    placeholder: '请输入手机号',
  },
])

/**
 * 表格列配置
 */
export const tableColumns = [
  {
    label: '用户',
    prop: 'userInfo',
    minWidth: 120,
    customRender: true,
    formatter: (row: any) => (row.userInfo ? row.userInfo.name : '-'),
  },
  {
    label: '酒店',
    prop: 'hotelInfo',
    minWidth: 150,
    customRender: true,
    formatter: (row: any) => row.hotelInfo.name,
  },
  {
    label: '房型',
    prop: 'houseType',
    minWidth: 100,
    formatter: (row: any, prop: string, value: any) => HOUSE_TYPES[value] || value || '-',
  },
  {
    label: '房间号',
    prop: 'houseNumber',
    minWidth: 100,
  },
  {
    label: '入住日期',
    prop: 'dwellStartDate',
    minWidth: 120,
    formatter: (row: any) => {
      return row.dwellStartDate ? dayjs(row.dwellStartDate).format('YYYY-MM-DD') : '-'
    },
  },
  {
    label: '离店日期',
    prop: 'dwellEndDate',
    minWidth: 120,
    formatter: (row: any) => {
      return row.dwellEndDate ? dayjs(row.dwellEndDate).format('YYYY-MM-DD') : '-'
    },
  },
  {
    label: '备注',
    prop: 'remark',
    minWidth: 150,
    showOverflowTooltip: true,
  },
  {
    label: '操作',
    prop: 'operations',
    width: 200,
    fixed: 'right',
    customRender: true,
  },
]

/**
 * 详情字段配置
 */
export const detailFields = [
  {
    label: '用户',
    prop: 'userInfo',
    render: (userInfo: any) => userInfo?.name || '-',
  },
  { label: '酒店', prop: 'hotelManagementId', render: (val: any) => getHotelName(val) },
  { label: '房型', prop: 'houseType', render: (val: any) => HOUSE_TYPES[val] || val || '-' },
  { label: '房间号', prop: 'houseNumber' },
  {
    label: '入住日期',
    prop: 'dwellStartDate',
    render: (val: any) => (val ? dayjs(val).format('YYYY-MM-DD') : '-'),
  },
  {
    label: '离店日期',
    prop: 'dwellEndDate',
    render: (val: any) => (val ? dayjs(val).format('YYYY-MM-DD') : '-'),
  },
  { label: '备注', prop: 'remark' },
  {
    label: '创建时间',
    prop: 'createdAt',
    render: (val: any) => (val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '-'),
  },
]

/**
 * 表单字段配置
 */
export const formFields = ref([
  {
    prop: 'userId',
    label: '用户',
    component: 'select',
    componentProps: {
      filterable: true,
      remote: true,
      reserveKeyword: true,
      clearable: true,
      options: userOptions,
      remoteMethod: (query: string) => {
        if (query) {
          console.log('远程搜索用户:', query)
          getPlayerList(query)
        }
      },
      onFocus: () => {
        // 预加载用户列表
        getPlayerList()
      },
      onChange: (value: any) => {
        console.log('选择的用户值:', value, typeof value)
        // 如果是对象，尝试提取id属性
        if (value && typeof value === 'object') {
          return value.value || value.id || value
        }
        return value
      },
      valueKey: 'value', // 指定值的属性名
      // 确保传入的值是字符串格式
      modelValue: (val: any) => {
        if (val && typeof val === 'object') {
          return val.value || val.id
        }
        return val
      },
    },
    rules: [{ required: true, message: '请选择用户', trigger: 'change' }],
  },
  {
    prop: 'hotelManagementId',
    label: '酒店',
    component: 'select',
    componentProps: {
      filterable: true,
      remote: true,
      reserveKeyword: true,
      clearable: true,
      options: hotelOptions,
      remoteMethod: (query: string) => {
        if (query) {
          console.log('远程搜索酒店:', query)
          getHotelList(query)
        }
      },
      onFocus: () => {
        // 预加载酒店列表
        getHotelList()
      },
      onChange: (value: any) => {
        console.log('选择的酒店值:', value, typeof value)
        // 如果是对象，尝试提取id属性
        if (value && typeof value === 'object') {
          return value.value || value.id || value
        }
        return value
      },
      valueKey: 'value', // 指定值的属性名
    },
    rules: [{ required: true, message: '请选择酒店', trigger: 'change' }],
  },
  {
    prop: 'houseType',
    label: '房型',
    component: 'select',
    componentProps: {
      filterable: true,
      clearable: true,
      options: houseTypeOptions,
    },
    rules: [{ required: true, message: '请选择房型', trigger: 'change' }],
  },
  {
    prop: 'houseNumber',
    label: '房间号',
    component: 'input',
    componentProps: {},
    rules: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  },
  {
    prop: 'dwellStartDate',
    label: '入住开始日期',
    component: 'date-picker',
    componentProps: {
      type: 'date',
      valueFormat: 'YYYY-MM-DD',
    },
    rules: [{ required: true, message: '请选择入住开始日期', trigger: 'change' }],
  },
  {
    prop: 'dwellEndDate',
    label: '入住结束日期',
    component: 'date-picker',
    componentProps: {
      type: 'date',
      valueFormat: 'YYYY-MM-DD',
    },
    rules: [{ required: true, message: '请选择入住结束日期', trigger: 'change' }],
  },
  {
    prop: 'remark',
    label: '备注',
    component: 'input',
    componentProps: {
      type: 'textarea',
      rows: 3,
    },
  },
])

/**
 * 格式化表单数据
 * @param formData 表单数据
 * @returns 格式化后的数据
 */
export const formatFormData = (formData: any): any => {
  const formattedData = { ...formData }

  // 添加活动ID
  formattedData.activityId = formattedData.activityId || localStorage.getItem('hongyouActId') || ''

  // 确保userId使用选择的用户ID
  if (formattedData.userId) {
    // 处理可能是对象的情况
    if (typeof formattedData.userId === 'object' && formattedData.userId !== null) {
      formattedData.userId = String(formattedData.userId.value || formattedData.userId.id || '')
    } else {
      formattedData.userId = String(formattedData.userId) // 确保userId是字符串格式
    }
    console.log('格式化后的userId:', formattedData.userId)
  }

  // 确保hotelManagementId使用选择的酒店ID
  if (formattedData.hotelManagementId) {
    // 处理可能是对象的情况
    if (typeof formattedData.hotelManagementId === 'object' && formattedData.hotelManagementId !== null) {
      formattedData.hotelManagementId = String(formattedData.hotelManagementId.value || formattedData.hotelManagementId.id || '')
    } else {
      formattedData.hotelManagementId = String(formattedData.hotelManagementId)
    }
    console.log('格式化后的hotelManagementId:', formattedData.hotelManagementId)
  }

  // 确保日期格式正确
  if (formattedData.dwellStartDate) {
    try {
      formattedData.dwellStartDate = dayjs(formattedData.dwellStartDate).format('YYYY-MM-DD')
    } catch (error) {
      console.error('格式化开始日期错误:', error)
    }
  }

  if (formattedData.dwellEndDate) {
    try {
      formattedData.dwellEndDate = dayjs(formattedData.dwellEndDate).format('YYYY-MM-DD')
    } catch (error) {
      console.error('格式化结束日期错误:', error)
    }
  }

  console.log('提交的表单数据:', formattedData)
  return formattedData
}

/**
 * 解析API返回的数据
 * @param apiData API返回的数据
 * @returns 解析后的数据
 */
export const parseApiData = (apiData: any): any => {
  if (!apiData) return {}

  const parsedData = {
    ...apiData,
    // 日期格式转换
    dwellStartDate: apiData.dwellStartDate || '',
    dwellEndDate: apiData.dwellEndDate || '',
  }

  // 确保userInfo存在，方便详情展示
  if (apiData.user && !apiData.userInfo) {
    parsedData.userInfo = apiData.user
  }

  // 如果存在userInfo，确保userId能正确回显
  if (parsedData.userInfo && parsedData.userInfo.id) {
    // 确保用户选项中包含当前用户
    const userOption = {
      value: String(parsedData.userInfo.id),
      label: parsedData.userInfo.name || `用户ID:${parsedData.userInfo.id}`,
    }

    // 检查是否已存在
    const existingOption = userOptions.value.find((opt) => String(opt.value) === String(userOption.value))
    if (!existingOption) {
      userOptions.value.push(userOption)
    }

    // 设置正确的userId，用于表单回显
    parsedData.userId = String(parsedData.userInfo.id)
  }

  console.log('解析后的数据:', parsedData)
  return parsedData
}

/**
 * 获取用户名称
 * @param userInfo 用户信息对象
 * @returns 用户名称
 */
export const getUserName = (userInfo: any): string => {
  if (!userInfo) return '-'

  // 如果是对象并且有name属性，返回name
  if (typeof userInfo === 'object' && userInfo.name) {
    return userInfo.name
  }

  // 如果只有ID，返回ID
  if (userInfo.id) {
    return `用户ID: ${userInfo.id}`
  }

  // 返回默认值
  return '-'
}

/**
 * 获取酒店名称
 * @param hotelId 酒店ID
 * @returns 酒店名称
 */
export const getHotelName = (hotelId: string | number): string => {
  if (!hotelId) return '-'

  // 先尝试直接通过stringId查找
  const stringId = String(hotelId)
  const hotel = hotelOptions.value.find((item) => String(item.value) === stringId)

  // 找到了直接返回名称
  if (hotel) return hotel.label

  // 找不到返回ID
  return `酒店ID: ${stringId}`
}

/**
 * 格式化日期
 * @param date 日期
 * @returns 格式化后的日期字符串
 */
export const formatDate = (date: string | Date): string => {
  return date ? dayjs(date).format('YYYY-MM-DD') : '-'
}
